package com.blqy.fr.user.api.login;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.blqy.fr.common.execption.BlQyException;
import com.blqy.fr.common.result.Result;
import com.blqy.fr.user.login.LoginAccount;
import com.blqy.fr.user.login.LoginClient;
import com.blqy.fr.user.login.LoginType;
import com.blqy.fr.user.service.MailService;
import com.blqy.fr.common.constant.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/auth")
@Slf4j
public class EmailLoginController {

    @Autowired
    private LoginClient loginClient;

    @Autowired
    private MailService mailService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/send-code")
    public Result<Object> sendCode(@RequestParam String email) {
        // 简单校验邮箱格式（可加强）
        if (!email.matches("^[\\w-]+@([\\w-]+\\.)+[\\w-]{2,4}$")) {
            return Result.fail().message("邮箱格式不正确");
        }

        // 生成6位数字验证码
        String code = RandomStringUtils.randomNumeric(6);

        // 发送邮件
        mailService.sendVerificationCode(email, code);

        // 存入 Redis，5分钟过期
        redisTemplate.opsForValue().set(
                RedisConstant.EMAIL_CODE_KEY_PREFIX + email,
                code,
                5,
                TimeUnit.MINUTES
        );

        return Result.ok("验证码已发送，请注意查收");
    }

    @PostMapping("/email-login")
    public Result<Object> emailLogin(@RequestBody LoginAccount account) {
        if (StringUtils.isBlank(account.getEmail()) || StringUtils.isBlank(account.getCode())) {
            return Result.fail().message("邮箱和验证码不能为空");
        }

        try {
            Map<String, Object> loginResult = loginClient.login(LoginType.EMAIL_LOGIN.type, account);
            return Result.ok(loginResult);
        } catch (BlQyException e) {
            return Result.fail().message(e.getMessage());
        } catch (Exception e) {
            log.error("邮箱登录异常", e);
            return Result.fail().message("系统异常，请稍后再试");
        }
    }
}